package com.linktrip.devicemanager.websocket.product;

import java.net.InetSocketAddress;
import java.util.List;
import java.util.concurrent.TimeUnit;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.linktrip.devicemanager.entity.DeviceInfo;
import com.linktrip.devicemanager.server.DeviceService;
import com.linktrip.devicemanager.util.Constant;
import com.linktrip.devicemanager.util.SpringContextUtil;
import com.linktrip.devicemanager.util.ToolKits;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.timeout.IdleStateHandler;

public class SocketServerThread extends Thread {
	Logger logger = LoggerFactory.getLogger(SocketServerThread.class);

	private static final int BOSS_GROUP_SIZE = Runtime.getRuntime().availableProcessors() * 2;
	private DeviceService deviceService = SpringContextUtil.getBean("deviceService");

	private int port = Constant.DEFAULT_PORT;
	ServerBootstrap serverBootstrap = null;
	EventLoopGroup bossGroup = null;
	EventLoopGroup workGroup = null;

	public SocketServerThread(int port) {
		if(port > 0)
			this.port = port;
	}

	protected static void bindConnectionOptions(ServerBootstrap bootstrap) {
		bootstrap.option(ChannelOption.SO_BACKLOG, Constant.DEFAULT_QUEUE_SIZE);
		bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10000);
		bootstrap.childOption(ChannelOption.TCP_NODELAY, true);
		bootstrap.option(ChannelOption.SO_RCVBUF, 1024);
		bootstrap.childOption(ChannelOption.SO_REUSEADDR, true); // 调试用
		bootstrap.childOption(ChannelOption.SO_KEEPALIVE, true); // 心跳机制暂时使用TCP选项，之后再自己实现
	}
	
	
	@Override
	public void run() {
		// TODO Auto-generated method stub
		super.run();
		initDevicesData();
		
		bossGroup = new NioEventLoopGroup(BOSS_GROUP_SIZE);
		workGroup = new NioEventLoopGroup();
		try {
			serverBootstrap = new ServerBootstrap();
			serverBootstrap.group(bossGroup, workGroup).channel(NioServerSocketChannel.class)
					.childHandler(new ChannelInitializer<SocketChannel>() {
						@Override
						protected void initChannel(SocketChannel channel) throws Exception {
							ChannelPipeline pipeline = channel.pipeline();
							pipeline.addLast("idleStateHandler",new IdleStateHandler(300,300,300,TimeUnit.SECONDS));
							pipeline.addLast(new LogicServerHandler());
						}
					});

			bindConnectionOptions(serverBootstrap);

			ChannelFuture f = serverBootstrap.bind(new InetSocketAddress(port)).awaitUninterruptibly();

			//ChannelFuture f = bootstrap.bind(port).sync();
			f.channel().closeFuture().sync();
		} catch (Exception e) {
			logger.error(e.getMessage());
			e.printStackTrace();
		} finally {
			workGroup.shutdownGracefully();
			bossGroup.shutdownGracefully();
		}
	}

	public void stopThread() {
		// serverBootstrap.
		if (workGroup != null)
			workGroup.shutdownGracefully();
		if (bossGroup != null)
			bossGroup.shutdownGracefully();
	}
	
	public void initDevicesData(){
		
		List<DeviceInfo> list = deviceService.listDeviceInfo();
		logger.info("devices list init size:{} ......",list != null?list.size():0);
		if(null != list){
			for (int i = 0;i<list.size();i++) {
				DeviceInfo info = list.get(i);
				ToolKits.addDeviceInfo(info.getDevice_no(), info);
				//logger.info("info:{}",info.toString());
			}
		}
	}

}
